package com.goalias.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.goalias.constant.SystemConstants;
import com.goalias.domain.dto.LoginDto;
import com.goalias.domain.entity.User;
import com.goalias.domain.vo.AdminInfoVo;
import com.goalias.domain.vo.LoginVo;
import com.goalias.exception.BizException;
import com.goalias.exception.ExceptionEnum;
import com.goalias.properties.JwtProperties;
import com.goalias.resp.Result;
import com.goalias.service.IUserService;
import com.goalias.utils.IoUtil;
import com.goalias.utils.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author goalias
 * @since 2024-12-02
 */
@RestController
@RequestMapping("/user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private IoUtil iOUtil;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        if (!StringUtils.hasText(loginDto.getUserName()) || !StringUtils.hasText(loginDto.getPassword())) {
            return Result.error(ExceptionEnum.REQUIRE_USER_INFO);
        }
        loginDto.setIp(IPUtil.getIp(request));
        loginDto.setAddress(IPUtil.getAddressByIP(loginDto.getIp()));
        LoginVo loginVo = userService.login(loginDto);
        if (loginVo == null) {
            return Result.error(ExceptionEnum.LOGIN_ERROR);
        }
        return Result.success(loginVo);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (!StringUtils.hasText(user.getUserName()) || !StringUtils.hasText(user.getPassword()) || !StringUtils.hasText(user.getPhone())) {
            return Result.error("注册信息缺失");
        }
        boolean register = userService.register(user);
        if (!register) {
            return Result.error("注册失败");
        }
        return Result.success();
    }

    @PostMapping("/logout")
    public Result logout(@RequestBody User user, HttpServletRequest request) {
        String tokenHeader = request.getHeader(jwtProperties.getJwtTokenName());
        if (!StringUtils.hasText(tokenHeader)) {
            return Result.error("登录token为空");
        }
        if (user.getId() == null){
            return Result.error("登录用户id为空");
        }
        userService.logout(user.getId(), tokenHeader);
        return Result.success();
    }

    @PostMapping("/updateInfo")
    @CacheEvict(value = "user", key = "#user.id")
    public Result updateInfo(@RequestBody User user) {
        if (ObjectUtil.isEmpty(user.getId())) {
            return Result.error("用户id为空");
        }
        boolean b = userService.updateInfo(user);
        if (!b) {
            return Result.error("用户更新失败");
        }
        return Result.success();
    }

    @PostMapping("/info")
    @Cacheable(value = "user", key = "#userId", unless = "#result==null", cacheManager = "redisCacheManager")
    public User info(@RequestBody Long userId) {
        User user = userService.getById(userId);
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }
        return user;
    }

    @GetMapping("/adminInfo")
    public Result adminInfo() {
        User admin = userService.getOne(new QueryWrapper<User>().eq("type", SystemConstants.ADMIN_USER));
        if (ObjectUtil.isEmpty(admin)) {
            throw new BizException(ExceptionEnum.DATABASE_ERROR);
        }
        admin.setAvatar(StringUtils.hasText(admin.getAvatar()) ?
                iOUtil.getUrl(iOUtil.getBUCKET_NAME(), admin.getAvatar())
                : iOUtil.getUrl(iOUtil.getBUCKET_NAME(),iOUtil.DEFAULT_AVATAR()));
        AdminInfoVo adminInfoVo = BeanUtil.copyProperties(admin, AdminInfoVo.class);
        return Result.success(adminInfoVo);
    }

}
